<template>
  <div class="articleList">
    <van-pull-refresh
     success-duration="1500"
     :success-text="pullRefeshText"
     v-model="isPullLoading"
     @refresh="onRefresh">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          :error.sync="error"
          error-text="请求失败，点击重新加载"
          @load="onLoad"
        >
        <Articleltem
        v-for="item in list"
        :key="item.art_id + ''"
        :articleItem='item'/>

        </van-list>
     </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import { Toast } from 'vant'
import Articleltem from '@/components/articleltem.vue'
export default {
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      preTimestamp: null,
      error: false, // 错误提示
      count: 0, // 下拉刷新
      isPullLoading: false,
      pullRefeshText: ''
    }
  },
  components: {
    Articleltem
  },
  created () {

  },

  methods: {
    // 列表初次显示
    // 加载的数据不能显示一整屏
    // 触底结束
    async onLoad () {
      try {
      //  1.发送请求获取数据
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: this.preTimestamp || Date.now(),
          with_top: 1
        })
        if (Math.random() > 0.5) {
          console.lg(12)
        }
        // 2.保存数据
        this.list.push(...res.results)
        this.preTimestamp = res.pre_timestamp
        // 3.加载状态结束
        this.loading = false
        // 4.数据全部加载完成
        if (!this.preTimestamp) {
        // 代表时间戳返回null
          this.finished = true
        }
      } catch (err) {
        Toast.clear()
        this.loading = false
        this.error = true
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
      //  1.发送请求获取数据
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 1
        })
        if (Math.random() > 0.5) {
          console.lg(1)
        }
        console.log(res)
        // 关闭下拉
        this.isPullLoading = false
        this.list.unshift(...res.results)
        this.pullRefeshText = '亲，共刷新' + res.results.length + '条数据'
      } catch (err) {
        // console.log('11')
        this.isPullLoading = false
        this.pullRefeshText = '亲，网络异常，稍后重试'
      }
    }
  }
}
</script>

<style scoped lang='less'>

  .articleList{
   height: 80vh;
   overflow-y:scroll;
  }
</style>
